package com.boco.fznq.network;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.transport.ServiceConnection;
import org.ksoap2.transport.ServiceConnectionSE;
import org.ksoap2.transport.Transport;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by jiangcheng on 2017/9/27.
 */

public class MyHttpTransport extends Transport {


    public MyHttpTransport(String url) {
        super(url);
    }

    @Override
    public void call(String soapAction, SoapEnvelope envelope) throws IOException, XmlPullParserException {
        if(soapAction == null) {
            soapAction = "\"\"";
        }

        byte[] requestData = this.createRequestData(envelope);
        this.requestDump = this.debug?new String(requestData):null;
        this.responseDump = null;
        ServiceConnection connection = this.getServiceConnection();
        connection.setRequestProperty("User-Agent", "kSOAP/2.0");
        connection.setRequestProperty("SOAPAction", soapAction);
        connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
        connection.setRequestProperty("Connection", "close");
        connection.setRequestProperty("Content-Length", "" + requestData.length);
        connection.setRequestMethod("POST");
        connection.connect();
        OutputStream os = connection.openOutputStream();
        os.write(requestData, 0, requestData.length);
        os.flush();
        os.close();
        Object requestData1 = null;

        Object is;
        try {
            connection.connect();
            is = connection.openInputStream();
        } catch (IOException var10) {
            is = connection.getErrorStream();
            if(is == null) {
                connection.disconnect();
                throw var10;
            }
        }

        if(this.debug) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[256];

            while(true) {
                int rd = ((InputStream)is).read(buf, 0, 256);
                if(rd == -1) {
                    bos.flush();
                    buf = bos.toByteArray();
                    this.responseDump = new String(buf);
                    ((InputStream)is).close();
                    is = new ByteArrayInputStream(buf);
                    break;
                }

                bos.write(buf, 0, rd);
            }
        }

        this.parseResponse(envelope, (InputStream)is);
    }

    protected ServiceConnection getServiceConnection() throws IOException {
        return new ServiceConnectionSE(this.url);
    }
}
